const eventEmitter = require('events');
const fs = require('fs');
const path = require('path');

const util = require('../../tools/util');
const _ = require('../../tools/_');

const schema = require('./schema');
const mime = require('./mime-type');

const mimeTypes = require('./mimes');


var col = db.collection('files');

var staticPath = path.resolve(__dirname, '../../', 'files/');
console.log(staticPath);

module.exports = class File {
  /**
   * @param {Object} file
   */
  constructor(file) {
    var self = this;

    file.extname = File.fileType(file.name);

    _.extend(self, file, schema);

    self.buffer = fs.readFileSync(file.path);

    self.hash = File.fileHash(self.buffer);

    // console.log(self);
  }

  /**
   *  保存图片
   * @return {Promise}
   */
  save() {
    var self = this;
    console.log('save file', self);
    return new Promise((resolve, reject) => {

      let folder = mime[self.extname];
      if (!folder) return reject(new Error('no access file type'));

      self.filename = (+new Date).toString(16) + self.name;
      mongo.findOne(col, { query: { hash: self.hash } }).then(doc => {
        if (doc) return resolve(doc);

        let filepath = path.resolve(staticPath, folder, self.filename);

        fs.writeFile(filepath,
          self.buffer,
          function(err) {
            if (err) return reject(err);

            delete self.buffer;

            self.path = filepath;
            self.filetype = folder;
            console.log(`write file ${self.name} success`);
            self.mimetype = mimeTypes[self.extname];
            mongo.insertOne(col, self).then(result => {
              self._id = result.insertedId;
              self.path = self.path.replace(/.+\/files/, '');

              resolve(self);
            }).catch(reject);

          });


      }).catch(reject);

      // mongo.insertOne(col, self).then(doc => {
      //   self._id = doc.insertedId;
      //   resolve(self);
      // }).catch(reject);
    });
  }


  static list(params, folder) {
    return new Promise((resolve, reject) => {
      var page = parseInt(params.page) || 0,
        num = parseInt(params.num) || 50;

      var query = { folder: folder || '' };
      mongo.find(col, {
        query,
        skip: page * num,
        limit: num,
        sort: {
          type: 1,
          createAt: -1
        }
      }).then(docs => {
        var result = Array.prototype.map.call(docs, function(item) {
          if (mime[item.extname] == 'image') {
            item.path = item.path.replace(/.+\/files/, '');
            return item;
          }
          return item;
        });
        // console.log(result);
        resolve(result);
      }).catch(reject);
    });
  }

  /**
   * 获取下载文件
   * @param {String} _id
   */
  static getDownloadFile(_id) {
    return new Promise((resolve, reject) => {
      mongo.findOneByObjectId(col, _id).then(doc => {
        if (!doc) return reject(new Error('file not found'));
        resolve(doc);
      }).catch(reject);
    });
  }

  /**
   * @param {String} filepath
   */
  static fileHash(file) {
    return util.sha1(file);
  }

  /**
   * @param {String} name
   */
  static fileType(name) {
    return path.extname(name).replace('.', '');
  }
};
